import { getGrayAuth } from '@src/api/SettingApi';
import { getRootWindow } from './dom';
import { GrayFunctionEnum, GrayFunctionObj } from 'pub-bbx-global/pageType/dist/grayFunction'
/**
 * @des 获取全局灰度的方法
 * @returns { GrayFunctionObj } 系统内的灰度参数具体参考接口返回值
 */
export function getAllGrayInfo():Promise<GrayFunctionObj>{
  try {
    let rootWindow = getRootWindow(window);
    // 首先从frame大框架去拿
    if(Reflect.has(rootWindow, 'grayAuth')){
      return Promise.resolve(rootWindow.grayAuth)
    }
    // 大框架中拿不到的情况单独调用接口去获取
    return getGrayAuth().then((res: any)=>{
      const { result, code } = res;
      if(code !== 0) throw 'getGrayAuth is Error'
      return result;
    })
  } catch (error) {
    console.warn(error, 'error try catch getAllGrayInfo');
    return Promise.reject('getAllGrayInfo fail')
  }
}

export function isOpenGrayByGrayFunctionName(grayFunctionName: keyof GrayFunctionObj): boolean {
  
  const rootWindow = getRootWindow(window);
  
  return Boolean(rootWindow?.grayAuth?.[grayFunctionName])
  
}

export function isOpenLinkCardGray(): boolean {
  // 表单设置连接器组件灰度
  // @ts-ignore
  return isOpenGrayByGrayFunctionName(GrayFunctionEnum.ConnectorFormControl)
}


export const isNewFaultLibraryGray = ()=>{
  return isOpenGrayByGrayFunctionName(GrayFunctionEnum.NewFaultLibraryGray)
}

/** 
 * @description 判断是否开启了触发器灰度
*/
export function isOpenTriggerGray(): boolean {
  const RootWindow = getRootWindow(window);
  return Boolean(RootWindow.grayAuth?.TRIGGER);
}

// 资质管理灰度
export function isQualification():boolean{
  return isOpenGrayByGrayFunctionName('CLOSE_OLD_QUALIFICATION')
}
/** 
 * @description 判断是否开启了人脸验证灰度
*/
export function haveFaceCheckGray(): boolean{
  return isOpenGrayByGrayFunctionName(GrayFunctionEnum.USERFACEAUTH)
}


export function haveProviderManager(){
  const RootWindow = getRootWindow(window)
  return isOpenGrayByGrayFunctionName('providerManager')
}

export function havePageButtonSetGray(){
  return isOpenGrayByGrayFunctionName(GrayFunctionEnum.CONTAINER)
}

// 判断是否开启了高级审批的灰度
export function haveEventVipApproveGray(): boolean{
  return isOpenGrayByGrayFunctionName(GrayFunctionEnum.EventVipApprove)
}

// 客户层级灰度
export function haveCustomerLevelGray(): boolean{
  return isOpenGrayByGrayFunctionName('CUSTOMER_HIERARCHY')
}
